<template>
	<view>
		<view class="detail-container" v-if="detail">
			<view class="image-container">
				<image :src="lost.picture" style="width: 100%;margin: 0 auto;"></image>
			</view>
			<u-cell-group>
				<u-cell size="large" title="失物招领标题" :value="lost.title">
				</u-cell>
				<u-cell size="large" title="失物招领内容" :value="lost.descrip">
				</u-cell>
				<u-cell size="large" title="发布时间" :value="lost.createTime">
				</u-cell>
				<u-cell size="large" title="找回状态" :value="lost.createTime">
					<text slot="value">{{lost.status === 0 ?'未认领找回':'已认领找回'}}</text>
				</u-cell>
			</u-cell-group>
			<text>发布人</text>
			<u-cell-group>
				<u-cell size="large" title="发布人头像">
					<image slot="value" :src="lost.avatar" style="width: 100px;" mode="widthFix"></image>
				</u-cell>
				<u-cell size="large" title="发布人昵称" :value="lost.nickname">
				</u-cell>
			</u-cell-group>
		</view>

		<view class="addOrUpdate-container" style="padding: 10px;" v-else>
			<u--form labelPosition="left" :model="lost" ref="form1">
				<u-form-item labelWidth=100 label="失物招领标题" prop="title" borderBottom ref="item1">
					<u--input v-model="lost.title" border="none" placeholder="请填写失物招领标题"></u--input>
				</u-form-item>
				<u-form-item labelWidth=100 label="失物招领描述" prop="descrip" borderBottom ref="item3">
					<u--textarea placeholder="请填写失物招领描述" v-model="lost.descrip"></u--textarea>
				</u-form-item>
				<u-form-item labelWidth=100px label="找回状态" prop="status" borderBottom
					@click="showStatus = true; hideKeyboard()" ref="item1" v-if="lost.id">
					<u--input v-model="lost.statusName" disabled disabledColor="#ffffff" placeholder="请选择找回状态"
						border="none" clearable></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item labelWidth=100px label="照片" prop="picture" borderBottom>
					<u-upload :previewFullImage="true" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic"
						name="1" :maxCount="1" @beforeRead="beforeRead"></u-upload>
				</u-form-item>
			</u--form>
			<u-action-sheet :show="showStatus" :actions="actions" title="请选择找回状态" @close="showStatus = false"
				@select="statusSelect">
			</u-action-sheet>

			<u-button type="primary" text="保存" customStyle="margin-top: 50px" @click="savaOrUpdate"></u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				authentication: '',
				fileList1: [],
				lost: {
					title: '',
					descrip: '',
					picture: '',
					status: 0,
				},
				detail: '',
				showStatus: false,
				actions: [{
						name: '未认领找回',
						value: 0
					},
					{
						name: '已认领找回',
						value: 1
					},
					{
						name: '取消',
						value: 2
					},
				],
				rules: {
					'title': {
						type: 'string',
						required: true,
						message: '此为必填字段',
						trigger: ['blur', 'change']
					},
					'descrip': {
						type: 'string',
						required: true,
						message: '请填写描述，你不描述我咋认领找回呢',
						trigger: ['blur', 'change']
					},
					'picture': {
						type: 'string',
						required: true,
						message: '必须上传照片哟！',
						trigger: ['blur', 'change']
					},
					'status': {
						type: 'number',
						min: 0,
						max: 1,
						required: true,
						message: '必须填写是否认领找回哦！',
						trigger: ['blur', 'change']
					}
				},
			};
		},
		onLoad(options) {
			// console.log(options);
			if (options.id) {
				if (options.type === 'detail') {
					this.detail = options.type
				}
				this.getById(options.id)
			}
			this.authentication = uni.getStorageSync('authentication')
		},
		onReady() {
			if (this.detail !== 'detail') {
				//onReady 为uni-app支持的生命周期之一
				this.$refs.form1.setRules(this.rules)
			}
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				// 用于存储符合条件的图片
				let Images = [];
				// 遍历上传的每张图片
				for (let i = 0; i < lists.length; i++) {
					const item = lists[i];
					// 验证图片格式
					const isImage = /\.(png|jpe?g)$/i.test(item.url);
					if (!isImage) {
						uni.showToast({
							title: '只能上传png，jpg，jpeg格式的图片',
							icon: 'none',
							duration: 3000
						});
						// 删除不符合条件的图片
						lists.splice(i, 1);
						// 跳过当前图片，进行下一张图片的验证
						continue;
					}
					// 验证图片大小
					const maxSize = 2 * 1024 * 1024; // 2MB大小限制
					if (item.size > maxSize) {
						uni.showToast({
							title: '图片大小不能超过2MB',
							icon: 'none',
							duration: 3000
						});
						// 删除不符合条件的图片
						lists.splice(i, 1);
						// 跳过当前图片，进行下一张图片的验证
						continue;
					}
					Images.push(item)
				}
				let fileListLen = this[`fileList${event.name}`].length
				Images.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < Images.length; i++) {
					const result = await this.uploadFilePromise(Images[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://localhost:8099/file/user/upload',
						filePath: url,
						name: 'pic',
						header: {
							'authentication': this.authentication
						},
						formData: {
							biz: 'lost_picture'
						},
						success: (res) => {
							// console.log(res);
							res = JSON.parse(res.data)
							if (res.code === 20000) {
								// console.log(res);
								this.lost.picture = res.data
								setTimeout(() => {
									resolve(res.data)
								}, 1000)
							} else {
								uni.$showMsg(res.msg)
							}
						}
					});
				})
			},
			savaOrUpdate() {
				console.log(this.lost);
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form1.validate().then(res => {
					if (this.lost.id) {
						this.updateById(this.lost.id)
					} else {
						this.saveLost()
					}
				}).catch(errors => {
					uni.$u.toast('保存失败！')
				})
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			statusSelect(e) {
				if (e.value === 2) {
					this.lost.statusName = ''
					this.lost.status = ''
					return
				}
				this.lost.status = e.value
				this.lost.statusName = e.name
			},
			async getById(id) {
				let {
					data: res
				} = await uni.$http.get('/user/lost/' + id)
				if (res.code === 20000) {
					this.lost = res.data
					this.fileList1.push({
						url: this.lost.picture
					})
					this.lost.statusName = this.lost.status === 0 ? '未认领找回' : '已认领找回'
				} else {
					uni.$showMsg(res.msg)
				}
			},
			async saveLost() {
				let {
					data: res
				} = await uni.$http.post('/user/lost', this.lost)
				if (res.code === 20000) {
					setTimeout(() => {
						uni.$showMsg("保存成功！")
					}, 1500)
					uni.navigateTo({
						url: '/pages/lostBoard/lostBoard'
					})
				} else {
					uni.$showMsg(res.msg)
				}
			},
			async updateById(id) {
				let {
					data: res
				} = await uni.$http.put('/user/lost/' + id, this.lost)
				if (res.code === 20000) {
					setTimeout(() => {
						uni.$showMsg("保存成功！")
					}, 1500)
					uni.navigateTo({
						url: '/pages/lostBoard/lostBoard'
					})
				} else {
					uni.$showMsg(res.msg)
				}
			},
		},
	}
</script>

<style lang="scss">

</style>